import {calc_distance} from "./utils.js"

class Bullet {
    constructor(weapon, start, end, config) {
        this.weapon = weapon;
        this.game = weapon.game;

        //{type: 1, bullet_power: 100, bullet_speed: 20, fire_interval: 200, fire_cell_range: 5}
        this.config = config;

        this.start_pos = start;
        this.position = start;
        this.end_pos = end;

        this.power = config.bullet_power;
    }

    move_on() {
        let [x1, y1] = this.position;
        let [x2, y2] = this.end_pos;

        let xx = Math.abs(x1 - x2);
        let yy = Math.abs(y1 - y2);
        // let xy = Math.sqrt(Math.pow(xx, 2) + Math.pow(yy, 2));
        let xy = calc_distance(this.position, this.end_pos);
        let speed_x = xx / xy * this.config.bullet_speed;
        let speed_y = yy / xy * this.config.bullet_speed;

        if (x2 > x1) {
            x1 += speed_x;
            x1 = x2 > x1 ? x1 : x2;
        }
        if (x2 < x1) {
            x1 -= speed_x;
            x1 = x2 < x1 ? x1 : x2;
        }
        if (y2 > y1) {
            y1 += speed_y;
            y1 = y2 > y1 ? y1 : y2;
        }
        if (y2 < y1) {
            y1 -= speed_y;
            y1 = y2 < y1 ? y1 : y2;
        }
        this.position = [x1, y1];
    }

    check_hit() {
        if (this.power === 0) return;

        let spirit_list = this.game.game_info.spirit_list;
        for (let i = 0; i < spirit_list.length; i++) {
            let spirit = spirit_list[i];
            let pos = spirit.position;
            let weight = spirit.config.weight;
            let fire_scale = spirit.config.fire_scale;

            let [x, y] = pos;
            let x1 = x - weight * fire_scale;
            let x2 = x + weight * fire_scale;
            let y1 = y - weight * fire_scale;
            let y2 = y + weight * fire_scale;

            let [x3, y3] = this.position;
            if (x3 >= x1 && x3 <= x2 && y3 >= y1 && y3 <= y2) {
                spirit.blood -= this.power;
                this.weapon.score += this.power;
                this.power = 0;
                break;
            }
        }
    }

    is_end() {
        let [x1, y1] = this.start_pos;
        let [x2, y2] = this.position;
        let [x3, y3] = this.end_pos;
        let xx = Math.abs(x1 - x2);
        let yy = Math.abs(y1 - y2);
        let xy = Math.sqrt(Math.pow(xx, 2) + Math.pow(yy, 2));

        let map_width = this.game.map.map_info.width;
        let map_height = this.game.map.map_info.height;
        return xy >= this.config.fire_range ||
            x2 <= 0 ||
            y2 <= 0 ||
            x2 >= map_width ||
            y2 >= map_height ||
            (x2 === x3 && y2 === y3) ||
            this.power === 0;
    }

    draw() {
        let [x, y] = this.position;
        let ctx = this.game.stage_canvas_ctx;

        ctx.fillStyle = "#0000ff";
        ctx.beginPath();
        ctx.arc(x, y, 5, 0, Math.PI * 2, true);
        ctx.fill();
    }
}

export default Bullet;